
import com.ba.baseandroid.LoginAbnormalInterceptor
import com.ba.baseandroid.App
import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import qsos.core.lib.config.CoreConfig
import qsos.core.lib.utils.json.DateDeserializer
import qsos.core.lib.utils.json.DateSerializer
import qsos.lib.netservice.IHttpConfig
import qsos.lib.netservice.interceptor.AddCookiesInterceptor
import qsos.lib.netservice.interceptor.NetworkInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit

class HttpConfig : IHttpConfig {

    override fun getOkHttpBuilder(): OkHttpClient.Builder {

        val mClient: OkHttpClient.Builder = OkHttpClient.Builder()
        // 设置自定义超时
        mClient.addInterceptor(SocketTimeInterceptor())
        // 网络连接性拦截器
        mClient.addInterceptor(NetworkInterceptor())
        // COOKIE拦截器
        mClient.addInterceptor(AddCookiesInterceptor())
        mClient.addNetworkInterceptor(LoginAbnormalInterceptor(App.myApplication().applicationContext))
        if (CoreConfig.DEBUG) {
            // 日志拦截器
            mClient.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }
        return mClient
    }

    override fun getRetrofitBuilder(): Retrofit.Builder {
        val mGsonBuilder = GsonBuilder()
        val mGsonConverterFactory: GsonConverterFactory

        // 配置请求时间解析，避免服务器返回的时间格式不一致导致的解析失败问题
        mGsonBuilder.registerTypeAdapter(Date::class.java, DateDeserializer())
            .setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        mGsonBuilder.registerTypeAdapter(Date::class.java, DateSerializer())
            .setDateFormat("yyyy-MM-dd HH:mm:ss").create()
        mGsonConverterFactory = GsonConverterFactory.create(mGsonBuilder.create())

        return Retrofit.Builder()
            .baseUrl(CoreConfig.BASE_URL)
            .addConverterFactory(mGsonConverterFactory)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    }
}

class SocketTimeInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val questUrl = request.url().toString()
        val timeOut: Int = when {
            questUrl.contains("rex2019s01-base-file-service") -> {
                600
            }
            else -> {
                12
            }
        }
        return chain.withConnectTimeout(timeOut, TimeUnit.SECONDS)
            .withReadTimeout(timeOut, TimeUnit.SECONDS)
            .withWriteTimeout(timeOut, TimeUnit.SECONDS)
            .proceed(request)
    }
}